/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using CookComputing.XmlRpc;

namespace Whitemice.ZOGI
{
  public class Enterprise : Company, IContactContainer, IProjectContainer, IZOGIStorable
  {
    protected MultiResultCallback projectCallback;
    
    public Enterprise() : base()
    {
      SetEntityName("Enterprise");
      SetVersion(0);
      SetHints(new string[] { "WRITE" });
      Bank = string.Empty;
      BankCode = string.Empty;
      EMail1 = string.Empty;
      Name = string.Empty;
      Keywords = string.Empty;
    }
          
    public Enterprise(IDictionary<string,object> x, int d)
      : base(x, d)
    {
    }
    
    internal override void Take(IDictionary<string,object> x, int d)
    {
		  base.Take(x, d);
			Bank = AsString(x, "bank");
			BankCode = AsString(x, "bankCode");
			EMail1 = AsString(x, "email");
			Name = AsString(x, "name");
			Keywords = AsString(x, "keywords");
      RequestProjects();
    }
    
		public string Bank { get; set; }
		public string BankCode { get; set; }
		public override string EMail1 { get; set; }
    public string Name { get; set; }		
		public string Keywords { get; set; }
		
    public override bool FirstClass { get { return true; } }
    
    public IEnumerable<int> ContactIds
    {
      get { return this.SubordinatesForKey("_CONTACTS"); }
    }

    public void GetContacts(MultiResultCallback _callback, object context)
    {
      FetchCommand command = new FetchCommand(ContactIds, 65535, context);
      command.Callback = _callback;
      Server.Connection.RunCommand(command);
    }

    public IEnumerable<int> ProjectIds
    {
      get { return this.SubordinatesForKey("_PROJECTS"); }
    }
    
    public void GetProjects(MultiResultCallback _callback, object context)
    {
      FetchCommand command = new FetchCommand(ProjectIds, 65535, context);
      command.Callback = _callback;
      Server.Connection.RunCommand(command);
    }
    
    protected Project _project = null;
    protected void RequestProjects()
    {
      FetchCommand command;
      
      if (projectCallback == null)
        projectCallback = new MultiResultCallback(ReceiveProjects);
      command = new FetchCommand(ProjectIds, 65535, null);
      command.Callback = projectCallback;
      Server.Connection.RunCommand(command);
    }
    protected void ReceiveProjects(object sender, RPCEventArgs args)
    {
      if (args.HasResults)
        foreach(Entity e in args.Payload)
          if ((e is Project) && (e as Project).IsPlaceHolder)
          {
            _project = (e as Project);
            break;
          }
    }
    public Project Project
    {
      get { return _project; }
    }
    
    public override void Assign(Entity _entity)
    {
      if (_entity is Whitemice.ZOGI.Contact)
      {
        // contact assignment
        AddSubordinate("_CONTACTS", _entity.ObjectId);
        _entity.AddSubordinate("_ENTERPRISES", ObjectId);
      } else if (_entity is Whitemice.ZOGI.Project)
				{
			    AddSubordinate("_PROJECTS", _entity.ObjectId);
					_entity.AddSubordinate("_ENTERPRISES", ObjectId);
				}
    } // end Assign
    
    public override void Unassign(Entity _entity)
    {
      if (_entity is Whitemice.ZOGI.Contact)
      {
        // contact assignment 
        RemoveSubordinate("_CONTACTS", _entity.ObjectId);            
        _entity.RemoveSubordinate("_ENTERPRISES", ObjectId);         
      } else if (_entity is Whitemice.ZOGI.Project)
        {
          // project assignment
          RemoveSubordinate("_PROJECTS", _entity.ObjectId);                 
          _entity.RemoveSubordinate("_ENTERPRISES", ObjectId);             
        } // end if-entity-is-project
    } // end Unassign
    
		public override XmlRpcStruct Encode()
		{
			XmlRpcStruct    rpcStruct;
			XmlRpcStruct[]  tmpArray;
			XmlRpcStruct    tmpStruct;
			int             count = 0;
			
			rpcStruct = base.Encode();
      rpcStruct.Add("entityName", "Enterprise");
      if (ObjectId < 0)
        rpcStruct.Add("objectId", 0);
        else rpcStruct.Add("objectId", ObjectId);
			rpcStruct.Add("bank", Bank);
			rpcStruct.Add("bankCode", BankCode);
			rpcStruct.Add("email", EMail1);
			rpcStruct.Add("keywords", Keywords);
			rpcStruct.Add("name", Name);
 			// Encode Contacts
 			count = 0;
 			tmpArray = new XmlRpcStruct[ContactIds.Count()];
 			foreach(int contactId in ContactIds)
 			{
 			  tmpStruct = new XmlRpcStruct();
 			  tmpStruct.Add("entityName", "assignment");
 			  tmpStruct.Add("targetEntityName", "Contact");
 			  tmpStruct.Add("targetObjectId", contactId);
 			  tmpStruct.Add("sourceObjectId", ObjectId);
 			  tmpStruct.Add("sourceEntityName", EntityName);
 			  tmpArray[count] = tmpStruct;
 			  count++;
 			}
 			rpcStruct.Add("_CONTACTS", tmpArray);
 			
			return rpcStruct;
		} // End Encode  
  } // end class
}
